﻿using Castle.Core.Logging;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using Inovout.Web.Mvc;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

namespace Inovout.Web
{
    public class WebComponentRegistrar : ComponentRegistrar
    {
        public override void Register()
        {
            Container.Register(Component.For<IControllerFactory>()
                .ImplementedBy<DefaultControllerFactory>()
                .DependsOn(Dependency.OnValue<IControllerActivator>(new ControllerComponentActivator())));
            this.Register(this.GetType().Assembly);
        }

        public override void Register(Assembly assembly)
        {
            Container.Register(
                Classes.FromAssembly(assembly)
                    .BasedOn<IController>()
                    .Configure(c => c.LifeStyle.Transient
                                    .Named(c.Implementation.FullName.ToLower())
                                    .OnCreate(BuildController)),
                    Classes.FromAssembly(assembly)
                    .BasedOn(typeof(IModelBinder))
                    .WithService.AllInterfaces()
                    //.Configure(delegate(ComponentRegistration component)
                    //{
                    //    component.LifeStyle.Transient.IsDefault();
                    //})
                );
            //处理js,css.aspx,cshtml,vbhtml
            foreach (string webResourceFileName in
                   assembly.GetManifestResourceNames().Where(fileName =>
                        webResourceFileExtensions.Contains(fileName.Substring(fileName.LastIndexOf(".")).ToLower())))
            {
                FileInfo fileInfo = new FileInfo(Application.Path + webResourceFileName);
                if (!fileInfo.Exists)
                {
                    using (FileStream fileStream = fileInfo.OpenRead())
                    {
                        assembly.GetManifestResourceStream(webResourceFileName).CopyTo(fileStream);
                    }
                }
            }
        }
        private readonly string[] webResourceFileExtensions = new string[] { "js", "css", "aspx", "cshtml", "vbshtml" };
        private void BuildController(IKernel kernel, object instance)
        {
            BaseController controller = instance as BaseController;
            if (controller != null && controller.Logger == null)
            {
                controller.Logger = kernel.Resolve<IExtendedLogger>();
            }

        }
    }
}
